﻿using Abp;
using Abp.Application.Services;
using FwProject.Manager;
using FwProject.ShopApplication;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Abp.ObjectMapping;
using FwProject.ShoppingMall.EventAdvertising;
using Abp.Domain.Repositories;
using X.PagedList;
using System.Linq;
using AutoMapper.QueryableExtensions;
using FwProject.ShoppingMall.Com;
using FwProject.Com.Dto;
using FwProject.ShoppingMall.Shop;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Uow;

namespace FwProject.Com.Dto
{
    /// <summary>
    /// 购物车管理
    /// </summary>
  
    public class ShopCarAppService : FwProjectAppServiceBase, IShopCarAppService
    {
        private readonly ShopCarManager _shopCarManager;
        private readonly IRepository<ShopCar, Guid> _shopCarRepository;
        private readonly IRepository<ShopProduct, Guid> _shopProductRepository;
        private readonly IRepository<ShopSecondkill, Guid> _shopSecondkillRepository;
        private readonly IRepository<ShopProductSku, Guid> _shopProductSkuRepository;
        private  Abp.IGuidGenerator _guid { get; set; }
        public  IObjectMapper _map { get; set; }
        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="shopCarManager"></param>
        /// <param name="shopCarRepository"></param>
        /// <param name="shopProductRepository"></param>
        /// <param name="shopSecondkillRepository"></param>
        /// <param name="shopProductSkuRepository"></param>
        public ShopCarAppService(ShopCarManager shopCarManager, IRepository<ShopCar, Guid> shopCarRepository, IRepository<ShopProduct, Guid> shopProductRepository,
            IRepository<ShopSecondkill, Guid> shopSecondkillRepository, IRepository<ShopProductSku, Guid> shopProductSkuRepository) {

            _shopCarManager = shopCarManager;
            _guid = SequentialGuidGenerator.Instance;
            _map = NullObjectMapper.Instance;
            _shopCarRepository = shopCarRepository;
            _shopProductRepository = shopProductRepository;
            _shopSecondkillRepository = shopSecondkillRepository;
            _shopProductSkuRepository = shopProductSkuRepository;
        }
        /// <summary>
        /// 创建一个购物车
        /// </summary>
        /// <param name="Input">创建模型</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<Guid> CreateShopCar(ShopCarInput Input)
        {
            var model = _map.Map<ShopCar>(Input);
            model.Id = _guid.Create();
            model.UserId = AbpSession.UserId.Value;
            return await _shopCarManager.CreateShopCar(model);
        }

        /// <summary>
        /// 多个商品一次性添加
        /// </summary>
        /// <param name="inputs">创建模型list</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task CreateListShopCar(List<ShopCarInput> inputs) {

            foreach (var input in inputs)
            {
                var model = _map.Map<ShopCar>(input);
                model.Id = _guid.Create();
                await _shopCarManager.CreateShopCar(model);
            }
        }
        /// <summary>
        /// 修改购物车的一个对象
        /// </summary>
        /// <param name="Id">主键</param>
        /// <param name="Input">修改模型</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task EditShopCar(ShopCarInput Input)
        {
              var model = _shopCarRepository.Get(Input.Id);
             model = _map.Map(Input, model);
             await _shopCarManager.UpdateShopCar(model);
        }
        /// <summary>
        /// 删除一个购物车对象
        /// </summary>
        /// <param name="Id">主键编号</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task CleanRemoveShopCar(Guid Id)
        {
            var model = _shopCarRepository.Get(Id);
            await _shopCarManager.DeleteShopCar(model);
        }

        /// <summary>
        /// 批量删除购物车明细
        /// </summary>
        /// <param name="guids">主键list对象</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task CleanRemoveListShopCar(List<CarId> guids)
        {
            foreach (var item in guids)
            {
                var model = _shopCarRepository.Get(item.Id);
                await _shopCarManager.DeleteShopCar(model);
            }
        }
        /// <summary>
        ///分页获取购物车查询
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        [AbpAuthorize]
        [UnitOfWork]
        public async Task<IPagedList<ShopCarDto>> GetPageList(int page,int pageSize) {

            var list = _shopCarRepository.GetAll().Where(o=>o.UserId==AbpSession.UserId.Value);
            var shopProduct = _shopProductRepository.GetAll();
            var listmodel = list.Join(shopProduct, o => o.ShopproductId, k => k.Id, (b, n) => new ShopCarDto
            {
                Id=b.Id,
                UserId = b.UserId,
                ShopproductId = b.ShopproductId,
                ProductCount = b.ProductCount,
                ShopSkuId = b.ShopSkuId,
                CreatorUserId = b.CreatorUserId,
                CreationTime = b.CreationTime,
                ShopProductCarDto =
                   new ShopProductCarDto
                   {
                       ShopTypeid = n.ShopTypeid,
                       ImagePic = n.ImagePic,
                       ProductName = n.ProductName,
                       ProductNumber = n.ProductName,
                       ProductDetails = n.ProductDetails,
                       Unit = n.Unit,
                       SpceWeight = n.SpceWeight,
                       ShopProductFlag=n.ShopProductFlag
                  }
            });
            var modellist = await listmodel.OrderByDescending(o => o.CreationTime).ToPagedListAsync(page, pageSize);
            for (int i = 0; i < modellist.Count(); i++)
            {
                modellist[i].ShopSkuName= _shopProductSkuRepository.Get(modellist[i].ShopSkuId).SpaceValueName;
                modellist[i].TempPrcie = modellist[i].ProductCount * ShopPrice(modellist[i].ShopSkuId, modellist[i]);
                if (modellist[i].ShopProductCarDto != null)
                {
                    modellist[i].ShopProductCarDto.SpcemarketPrice = ShopPrice(modellist[i].ShopSkuId, modellist[i]);
                }
            }
           
            return  modellist ;
        }

        /// <summary>
        /// 获取购物车中的单个商品
        /// </summary>
        /// <param name="shopId">商品编号</param>
        /// <returns></returns>

        public ShopCarDto GetProductByIdCar(Guid shopId)
        {
            var list = _shopCarRepository.GetAll().Where(o => o.UserId == AbpSession.UserId.Value && o.ShopproductId== shopId);
            var shopProduct = _shopProductRepository.GetAll();
            var listmodel = list.Join(shopProduct, o => o.ShopproductId, k => k.Id, (b, n) => new ShopCarDto
            {
                Id = b.Id,
                UserId = b.UserId,
                ShopproductId = b.ShopproductId,
                ProductCount = b.ProductCount,
                ShopSkuId = b.ShopSkuId,
                CreatorUserId = b.CreatorUserId,
                CreationTime = b.CreationTime,
                
                ShopProductCarDto =
                   new ShopProductCarDto
                   {
                       ShopTypeid = n.ShopTypeid,
                       ImagePic = n.ImagePic,
                       ProductName = n.ProductName,
                       ProductNumber = n.ProductName,
                       ProductDetails = n.ProductDetails,
                       SpceWeight = n.SpceWeight,
                       Unit = n.Unit,
                       ShopProductFlag = n.ShopProductFlag
                   }
            });
            var model=  listmodel.OrderByDescending(o => o.CreationTime).FirstOrDefault();
            if (model != null)
            {
                model.TempPrcie = model.ProductCount * ShopPrice(model.ShopSkuId, model);
                model.ShopSkuName= _shopProductSkuRepository.Get(model.ShopSkuId).SpaceValueName;

                if (model.ShopProductCarDto != null) {
                    model.ShopProductCarDto.SpcemarketPrice = ShopPrice(model.ShopSkuId, model);
                }
                  
            }
            return model;
        }

        /// <summary>
        /// 获取当前购物车的总数
        /// </summary>
        /// <returns></returns>

        public int GetCarCount() {
            if (AbpSession.UserId == null)
                return 0;

            return _shopCarRepository.GetAll().Where(o => o.UserId == AbpSession.UserId.Value).Sum(o=>o.ProductCount);

        }
        /// <summary>
        /// 获取当前产品在购物车中的数量
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public int GetShopCarCount(Guid shopId) {

            if (AbpSession.UserId == null)
                return 0;

            return _shopCarRepository.GetAll().Where(o => o.UserId == AbpSession.UserId.Value && o.ShopproductId==shopId).Sum(o => o.ProductCount);
        }

        /// <summary>
        /// 根据商品实际情况判断获取商品的实际价格
        /// </summary>
        /// <param name="shopSkuId"></param>
        /// <param name="shopProduct"></param>
        /// <returns></returns>
        public decimal ShopPrice(Guid shopSkuId,  ShopCarDto shopProduct) {

            decimal m = shopProduct.ShopProductCarDto.SpcemarketPrice;
            var model = _shopProductSkuRepository.Get(shopSkuId);
                if (shopSkuId != Guid.Empty) {
                  
                    m = model.SpceMarketPrice;

                }
            return m;
        }
    }
}
